#include "LinkList.h"
using namespace CSCI123;

LinkList::LinkList(): mHead(NULL), mSize(0) {
	/* constructs an empty list */
}

LinkList::~LinkList() {
	// delete all the nodes in the list
	NodePtr targetPtr = mHead;

	while(mHead != NULL) {
		targetPtr = mHead;
		mHead = targetPtr->next;
		delete targetPtr;
		targetPtr = NULL;	// Here I set target to NULL for readability
		mSize--;					
	}
	mHead = NULL;
	mSize = 0;
}

void LinkList::insert(const string& aData) {
	// Construct a new node
	NodePtr aNode = new Node;
	aNode->data = aData;
	aNode->next = mHead;	// now head and aNode
				// pt to the first node
	mHead = aNode;		// now head pts to the first
	mSize++;
}

bool LinkList::insert(const string& aData1, const string& aData2) {
	NodePtr cur = mHead;
	bool found = false;
	// search for the data to place data2 after
	while(cur != NULL) {
		if(cur->data == aData1) {
			found = true;
			break;
		}
		cur = cur->next;	// go to the next node and test
	}
	if(found) {
		// Construct a new node
		NodePtr aNode = new Node;
		aNode->data = aData2;		// set the data to the string
		aNode->next = cur->next;	// set next ptr to the node after cur
		cur->next = aNode;		// set cur to point to the new node
		mSize++;
	}
	return false;
}

// this is potentially dangerous
// what happens if we don't return this by reference?
void LinkList::search(NodePtr& cur, const string& target) const {
	// transverse the list till we find what we are looking for
	for(cur = mHead; cur != NULL; cur = cur->next) {
		if(cur->data == target) {
			return;		// found the node, return
		}		
	}
	// if the target is not found we set cur to NULL
	cur = NULL;
}

void LinkList::deleteNode(const string& aData) {	
	NodePtr targetPtr = mHead;
	NodePtr prevPtr = NULL;		// no previous for the first node

	if(targetPtr == NULL)
		return;
	
	for(;targetPtr != NULL;) {
		if(targetPtr->data == aData) {
			if(prevPtr == NULL) {
				mHead = targetPtr->next;
			} else {
				prevPtr->next = targetPtr->next;
			}
			delete targetPtr;
			targetPtr = NULL;
			mSize--;
		} else {
			prevPtr = targetPtr; 
			targetPtr = targetPtr->next;
		}
	}
}

int LinkList::getSize() const {
	return mSize;
}

bool LinkList::isEmpty() const {
	return mSize == 0;
}
